<?php

namespace src\common;

final class RouterMatch
{
    private static $routes = [];

    private static function loadAllConfig() {

        // 获取所有的路由配置，并合并到一个数组中
        $router_configs = glob(ROUTER_DIR . '*.php', GLOB_NOSORT);
        foreach ($router_configs as $router_config) {
            $_router_config = require_once($router_config);
            if (is_array($_router_config) && $_router_config) {
                self::$routes = [self::$routes, ...$_router_config];
            }
        }
    }

    public static function match()
    {

        self::loadAllConfig();

        if (!self::$routes) {
            Response::err('No routes found');
        }

        // 获取当前请求的路径
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = strtolower($_SERVER['REQUEST_METHOD']);

        // 匹配路由
        if (array_key_exists($path, self::$routes)) {
            $_path = self::$routes[$path];
            $_m = ['get']; // 默认为get
            $_p = '';
            if (is_array($_path)) {
                $_p = $_path[0];
                $_m = explode('|', strtolower($_path[1]));
            } else {
                $_p = $_path;
            }

            if (in_array($method, $_m)) {
                // 直接匹配的情况
                [$controller, $action] = explode('@', $_p);
            }
        }

        // 如果没有找到匹配的路由，显示 404 错误
        if (!isset($controller)) {
            Response::err('404 Not Found', 404);
        }

        return [$controller, $action];

    }
    
}
